<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\policyMatching\controller;

use plugin\saiadmin\basic\BaseController;
use app\policyMatching\logic\PolicyMatchingLogic;
use app\policyMatching\validate\PolicyMatchingValidate;
use support\Request;
use support\Response;
use think\facade\Db;

/**
 * 政策匹配控制器
 */
class PolicyMatchingController extends BaseController
{
    /**
     * 数据表主键
     */
    protected $pk = 'matching_id';
    
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new PolicyMatchingLogic();
        $this->validate = new PolicyMatchingValidate;
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['policy_title', ''],
            ['lang_code', 'zh'],
            ['application_start_time',[]],
            ['application_end_time',[]],
            ['is_display',''],
            ['xz_level','']
        ]);
        $query = $this->logic->search($where) ->order('sort_order desc,create_time desc');
        $data = $this->logic->getList($query);
        return $this->success($data);
    }
    public function updateSortOrder(Request $request) : Response
    {
        $id = $request->input('id', '');
        $sort_order = $request->input('sort_order', 1);
        
       
        $result = $this->logic->where($this->pk, $id)->update(['sort_order' => $sort_order,'update_time'=>date('Y-m-d H:i:s')]);
          
        if ($result) {
            // $this->afterChange('changeStatus');
            return $this->success('操作成功');
        } else {
            return $this->fail('操作失败');
        }
    }
    public function changeStatus(Request $request) : Response
    {
        $id = $request->input('id', '');
        $status = $request->input('status', 1);
        $result = $this->logic->where($this->pk, $id)->update(['is_display' => $status]);
        if ($result) {
            $this->afterChange('changeStatus');
            return $this->success('操作成功');
        } else {
            return $this->fail('操作失败');
        }
    }
    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        // 获取 POST 请求数据
        $data = $request->post();

        // 数据验证
        if ($this->validate && !$this->validate->scene('save')->check($data)) {
            return $this->fail($this->validate->getError());
        }

        try {
            // 开启数据库事务
            Db::startTrans();

            // 创建主记录
            $result = $this->logic->createData($data);
            if(!$result)throw new \Exception('添加失败');

            if ($result && isset($data['industry_category']) && !empty($data['industry_category'])) {
                // 准备关联数据
                $industryCategoryValues = $this->prepareIndustryCategoryValues($data['industry_category'], $result->matching_id);

                // 插入关联数据
                if (!empty($industryCategoryValues) && !Db::table('eb_policy_matching_search')->insertAll($industryCategoryValues)) {
                    throw new \Exception('关联数据插入失败');
                }
            }

            // 提交事务
            Db::commit();
            $this->afterChange('save');
            return $this->success('操作成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->fail('操作失败: ' . $e->getMessage());
        }
    }

    /**
     * 修改数据
     * @param Request $request
     * @param mixed $id
     * @return Response
     */
    public function update(Request $request, $id): Response
    {
        // 获取请求中的 ID
        $id = $request->input('id', $id);
        // 获取 POST 请求数据
        $data = $request->post();

        // 数据验证
        if ($this->validate && !$this->validate->scene('update')->check($data)) {
            return $this->fail($this->validate->getError());
        }

        // 查找要更新的记录
        $info = $this->logic->find($id);
        if (!$info) {
            return $this->fail('没有找到该数据');
        }

        try {
            // 开启数据库事务
            Db::startTrans();

            if (isset($data['industry_category']) && !empty($data['industry_category'])) {
                // 准备关联数据
                $industryCategoryValues = $this->prepareIndustryCategoryValues($data['industry_category'], $id);

                // 删除旧的关联数据
                Db::table('eb_policy_matching_search')->where('matching_id', $id)->delete();

                // 插入新的关联数据
                if (!empty($industryCategoryValues) && !Db::table('eb_policy_matching_search')->insertAll($industryCategoryValues)) {
                    throw new \Exception('关联数据插入失败');
                }
            }

            // 更新主记录
            $result = $this->logic->update($data, [$this->pk => $id]);
            if(!$result){
                throw new \Exception('更新失败');
            }

            // 提交事务
            Db::commit();
            $this->afterChange('update');
            return $this->success('操作成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->fail('操作失败: ' . $e->getMessage());
        }
    }

    /**
     * 准备行业分类关联数据
     * @param array $industryCategory 行业分类数据
     * @param mixed $matchingId 匹配 ID
     * @return array 准备好的关联数据
     */
    private function prepareIndustryCategoryValues(array $industryCategory, $matchingId): array
    {
        $values = [];
        foreach ($industryCategory as $val) {
            if(!empty($val)){
                foreach ($val as $v) {
                    $values[] = [
                        'industry_category_id' => $v,
                        'matching_id' => $matchingId
                    ];
                }
            }
        }
        return $values;
    }

}
